package edu.wtbu.cs.androiddemo.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.ArrayList;
import java.util.List;

import edu.wtbu.cs.androiddemo.MainActivity;
import edu.wtbu.cs.androiddemo.R;

public class UIMessageSampleActivity extends AppCompatActivity {

    private static final String DATA_NUM= "num";

    private static final String RESULT_KEY= "result_key";

    private static final String logTag=UIMessageSampleActivity.class.getName();
    TextView result;
    EditText  editText;

    CalThread calThread;

    /**
     * 主UI线程处理消息，接受计算结果，并渲染到界面
     */
    Handler mUiHandler =new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what==0x111){
                result.setText(msg.getData().getString(RESULT_KEY));
                Log.i("mUiHandler Thread-->",Thread.currentThread().getName());

            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_uimessage_sample);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        editText = findViewById(R.id.edit);
        result = findViewById(R.id.result);
        calThread = new CalThread();
        calThread.start();
    }

    //通过handler更新UI
    public void onClickCalButton(View view){
        Message message = new Message();
        message.what = 0x110;
        Bundle bundle = new Bundle();
        bundle.putInt(DATA_NUM,Integer.parseInt(editText.getText().toString()));
        message.setData(bundle);

        //模拟主线程中执行耗时操作，导致界面卡死
//        try {
//            Thread.sleep(10*1000);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
        calThread.mHandler.sendMessage(message);

    }

    public void onClickRunOnUIThreadDemo(View view){
        Log.i(logTag,"onClickRunOnUIThreadDemo");
        int num = Integer.parseInt(editText.getText().toString());
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.i("onClickRunOnUIThreadDemo-->","onClickRunOnUIThreadDemo--->"+Thread.currentThread().getName());
                List<Integer> nums =   calPrime(num);
                UIMessageSampleActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        result = findViewById(R.id.result);
                        result.setText("【计算结果】:"+nums.toString());
                        Log.i("onClickRunOnUIThreadDemo-->","onClickRunOnUIThreadDemo--->"+Thread.currentThread().getName());
                    }
                });
            }
        }).start();
    }

    //

    /**
     * 计算质数的线程
     */
    class CalThread extends Thread {

        public Handler mHandler;
        @Override
        public void run() {
            //todo
            Looper.prepare();
            mHandler = new Handler(){
                @Override
                public void handleMessage(@NonNull Message msg) {
                    super.handleMessage(msg);
                    if (msg.what == 0x110){
                        int num = msg.getData().getInt(DATA_NUM);
                        List<Integer> nums = calPrime(num);
                        Toast.makeText(UIMessageSampleActivity.this,"计算质数结果是："+nums.toString(),Toast.LENGTH_LONG).show();
                        Message message = new Message();
                        message.what = 0x111;
                        Bundle bundle =new Bundle();
                        bundle.putString(RESULT_KEY,nums.toString());
                        message.setData(bundle);
                        //向主UI线程 发生消息
                        mUiHandler.sendMessage(message);
                        Log.i("CalThread-->",Thread.currentThread().getName());
                    }
                }
            };
            Looper.loop();
        }

        //计算质数

    }


    private List<Integer> calPrime(int num){
        List<Integer> nums = new ArrayList<>();
        for(int i=2;i<= num ;i++){
            boolean isAdd = true;
            for(int j = 2 ; j<= Math.sqrt(i);j++){
                if (i!=2 && i%j==0){
                    isAdd=false;
                    continue;
                }
            }
            if (isAdd)
                nums.add(i);

        }
        try {
            Thread.sleep(5*1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return nums;
    }


    public void clickListDialogMultiChoice(View view){
        Log.i(logTag, "clickListDialogMultiChoice");
        AlertDialog.Builder builder = new AlertDialog.Builder(UIMessageSampleActivity.this);
        builder.setTitle("多选对话框");
        final String[] items = {"数学","语文","英语","政治"};
        final boolean[] checkItems = {false,true,false,false};
        builder.setMultiChoiceItems(items, checkItems, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                if (isChecked){
                    checkItems[which]=true;
                }else {
                    checkItems[which]=false;
                    Toast.makeText(UIMessageSampleActivity.this,"您取消了"+items[which],Toast.LENGTH_LONG).show();
                }
            }
        });


        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String checkItem = "";
                for (int i=0;i< checkItems.length;i++){
                    if ( checkItems[i]==true)
                        checkItem=checkItem+items[i];
                }

                Toast.makeText(UIMessageSampleActivity.this,"您选择了："+checkItem,Toast.LENGTH_LONG).show();
            }
        });
        builder.create().show();

    }

    /**
     * 单选对话框
     * @param view
     */
    public void clickListDialogSingleChoice(View view){
        Log.i(logTag, "clickListDialogSingleChoice");
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("单选对话框");
        final String[] items = {"男","女"};
        final boolean[] checkItems = {true,false};
        builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                for (int i=0;i< checkItems.length;i++){
                    checkItems[i]=false;
                }
                checkItems[which]=true;
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
//                Toast.makeText(MainActivity.this,"您单击了取消按钮",Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String checkItem = "";
                for (int i=0;i< checkItems.length;i++){
                    if ( checkItems[i]==true)
                        checkItem=items[i];
                }

                Toast.makeText(UIMessageSampleActivity.this,"您选择了："+checkItem,Toast.LENGTH_LONG).show();
            }
        });
        builder.create().show();
    }

}